package com.tc.itfarm.web.action.code;

import com.tc.itfarm.api.common.Codes;
import com.tc.itfarm.api.enums.QueryArticleEnum;
import com.tc.itfarm.api.model.Page;
import com.tc.itfarm.api.model.PageList;
import com.tc.itfarm.model.Article;
import com.tc.itfarm.model.User;
import com.tc.itfarm.service.*;
import com.tc.itfarm.web.action.BaseAction;
import com.tc.itfarm.web.biz.ArticleBiz;
import com.tc.itfarm.web.vo.MenuVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/code")
public class CodeAction extends BaseAction{

	/**
	 * 文章首页
	 * @param request
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request, @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo) {
		ModelAndView mv = new ModelAndView("code/index");
		Page page = new Page(pageNo, Codes.INDEX_PAGE_SIZE);
		PageList<Article> articlePageList = articleService.selectCodeArticleByPage(page, null);
		mv.addObject("articles", articleBiz.getArticleVOs(articlePageList.getData()));
		mv.addObject("page", articlePageList.getPage());
		this.addAttribute(mv, request);
		// 菜单默认选择首页
		mv.addObject("menuSelected", 1);
		return mv;
	}

	/**
	 * 下一页
	 * @param request
	 * @return
	 */
	@RequestMapping("/nextPage")
	public ModelAndView nextPage(HttpServletRequest request, @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo) {
		ModelAndView mv = new ModelAndView("article/article_page");
		Page page = new Page(pageNo, Codes.INDEX_PAGE_SIZE);
		PageList<Article> articlePageList = articleService.selectCodeArticleByPage(page, null);
		mv.addObject("articles", articleBiz.getArticleVOs(articlePageList.getData()));
		mv.addObject("page", articlePageList.getPage());
		return mv;
	}

	/**
	 * 初始化数据
	 * @param mv
	 */
	private void addAttribute(ModelAndView mv, HttpServletRequest request) {
		// 用于图片滑动展示
		mv.addObject("animations", articleBiz.getArticleVOs(articleService.selectArticles(QueryArticleEnum.PAGE_VIEW, 5)));
		mv.addObject("newArticles", articleBiz.getArticleVOs(articleService.selectArticles(QueryArticleEnum.CREATE_TIME, 5)));
		// 最新评论
		mv.addObject("comments", commentService.selectRecent10());
        User u = (User) request.getSession().getAttribute("user");
	}

}
